//
//  RecommendedTableViewController.m
//  BJS151148-Team8
//
//  Created by lanou3g on 16/3/22.
//  Copyright © 2016年 hyy. All rights reserved.
//

#import "RecommendedTableViewController.h"
#import "TravelHelper.h"
#import "RecommendModel.h"
#import "SDCycleScrollView.h"
#import "GiFHUD.h"
#import "HeadTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "CFCoverFlowView.h"
#import "storyTableViewCell.h"
@interface RecommendedTableViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource,SDCycleScrollViewDelegate>
/** 所有的Model数组 */
/** 每日精选故事 */
@property (nonatomic, strong) NSMutableArray *storyArray;
/** 游记专题 */
@property (nonatomic, strong) NSMutableArray *specialArray;
/** 用于上拉加载使用 */
@property (nonatomic, copy) NSString *next_start;

/** 轮播图数数据源 */
@property (nonatomic, strong) NSMutableArray *lunBoTuArray;


@end

@implementation RecommendedTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    [self.tableView registerClass:[HeadTableViewCell class] forCellReuseIdentifier:@"pics"];
   
    // 热门游记cell
    [self.tableView registerNib:[UINib nibWithNibName:@"storyTableViewCell" bundle:nil] forCellReuseIdentifier:@"storyTableViewCell"];
    
    self.navigationItem.title = @"记忆旅行";
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:19]}];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"附近" style:UIBarButtonItemStyleDone target:self action:@selector(rightButtonAction)];
    
//    皮卡丘
//    [GiFHUD setGifWithImageName:@"pika.gif"];
//    [GiFHUD show];


    [self handleData];
    

}



-(void)rightButtonAction{


    

}

-(void)handleData{
//  初始化
    self.lunBoTuArray = [NSMutableArray array];
    self.storyArray = [NSMutableArray array];
    self.specialArray = [NSMutableArray array];
    
    [[TravelHelper defaultTravelHelper] get:@"http://api.breadtrip.com/v2/index/?lat=40.02930237016372&lng=116.3375773078163&sign=88bd8daa381a99f87acfa8c0c2aaf568" params:nil success:^(id responseObj) {
       
        for (NSDictionary *dic in responseObj[@"data"][@"elements"]) {
//            NSLog(@"%@",dic[@"desc"]);
            if ([dic[@"desc"] isEqualToString:@"广告banner"]) {
                for (NSDictionary *dict in [dic[@"data"] lastObject]) {
//                    NSLog(@"%@",dict);
                    
                    RecommendModel *recomendModel = [[RecommendModel alloc] init];
                    [recomendModel setValuesForKeysWithDictionary:dict];
                    [self.lunBoTuArray addObject:recomendModel];
//                    NSLog(@"%@",self.lunBoTuArray);
                }
                
                // 加载轮播图
                [self LunBoTuView];
                
            }else if ([dic[@"desc"] isEqualToString:@""]){
                for (NSDictionary *dict1 in dic[@"data"]) {
                    
                    RecommendModel *recommend = [[RecommendModel alloc] init];
                    
                    if (![dict1.allKeys containsObject:@"title"]) {
                        [recommend setValuesForKeysWithDictionary:dict1];
                        
                        // 用户
                        [recommend setValuesForKeysWithDictionary:dict1[@"user"]];
                        [recommend setValue:dict1[@"user"][@"name"] forKey:@"user_name"];
//                        NSLog(@"%@", dict1[@"poi"]);
                        if ([dict1[@"poi"] isKindOfClass:[NSDictionary class]]) {
                            // poi字典
                            [recommend setValue:dict1[@"poi"][@"name"] forKey:@"poi_name"];
                            [recommend setValuesForKeysWithDictionary:dict1[@"poi"]];
                        }
                        [self.storyArray addObject:recommend];
//                        NSLog(@"%@", self.storyArray);
                    }
                    
                }
                
            }else{
                // 精彩热门游记
                for (NSDictionary *dict1 in dic[@"data"]) {
                    RecommendModel *recommend = [[RecommendModel alloc] init];
                    [recommend setValue:dict1[@"id"] forKey:@"ID"];
                    //NSLog(@"----%@", recommend.name);
                    if (![dict1.allKeys containsObject:@"title"]) {
                        [recommend setValuesForKeysWithDictionary:dict1[@"user"]];
                        [recommend setValuesForKeysWithDictionary:dict1];
                        [recommend setValuesForKeysWithDictionary:dic];
                        // 用户字典赋值
                        [recommend setValue:dict1[@"user"][@"name"] forKey:@"user_name"];
                        [self.specialArray addObject:recommend];
//                        NSLog(@"%@",self.specialArray);
                    }
                    
                }
            }

        }
        [GiFHUD dismiss];
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"系统提示" message:@"网络链接失败,请查看网络连接" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [view show];
        
    }];
   


}


// 轮播图
-(void)LunBoTuView{

   // 保存图片
    _headimage = [NSMutableArray array];
    
    for (int i = 0; i < self.lunBoTuArray.count; i++) {
        
        RecommendModel *model = self.lunBoTuArray[i];
        
//        [imageView sd_setImageWithURL:[NSURL URLWithString:model.image_url]]
        
        [_headimage addObject:model.image_url];
        
        
    }
   
}

//// 轮播图点击事件
//- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
//    RecommendModel *model = self.lunBoTuArray[index];
//    
//    nextLunBoTunController *nextVC = [[nextLunBoTunController alloc]init];
//    nextVC.model = model;
//    [self.navigationController pushViewController:nextVC animated:YES];
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.specialArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 1;
    }
    return self.specialArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        return 150;
    }
    return self.view.frame.size.height * 0.35;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        HeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pics" forIndexPath:indexPath];
        
        if (cell == nil) {
            cell = [[HeadTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"pics"];
        }

//        判断tag值
        if (self.headimage.count > 0) {
            
            CFCoverFlowView *view = [cell viewWithTag:999];
        
            [view setPageItemsWithImageNames:self.headimage];
//            NSLog(@"%@",self.headimage);
        }
        
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        
        return cell;
    }
    else {
        RecommendModel *model = self.specialArray[indexPath.row];
        if ([model.type integerValue] == 4 || [model.type integerValue] == 12) {
            storyTableViewCell *hotcell = [[storyTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"storyTableViewCell"];
        
        RecommendModel *model = self.specialArray[indexPath.row];
        hotcell.titlelabel.text = model.name;
         hotcell.titlelabel.font = [UIFont boldSystemFontOfSize:20.0f];
        
        [hotcell.backImageView sd_setImageWithURL:[NSURL URLWithString:model.cover_image] placeholderImage:[UIImage imageNamed:@"cat"] options:SDWebImageCacheMemoryOnly completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
        }];

        
        
        return hotcell;
    }
   }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(10, 5, 5, CGRectGetHeight(view.frame) - 10)];
    view1.backgroundColor = [UIColor colorWithRed:0.2 green:0.45 blue:0.1 alpha:0.87];
    [view addSubview:view1];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, self.view.frame.size.width * 0.5, CGRectGetHeight(view.frame))];
    [view addSubview:label];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 50, 0, 50, CGRectGetHeight(view.frame))];
    [button setBackgroundImage:[UIImage imageNamed:@"iconfont-i"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    view.backgroundColor = [UIColor whiteColor];
    if (section == 1) {
        label.text = @"每日精选故事";
        return view;
    }

    if (section == 2) {
        [button removeFromSuperview];
        label.text = @"精彩游记和专题";
        return view;
    }
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

-(void)buttonAction{

    

}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
